Imports System.Windows.Forms

Public Class AddTemplate
  Private _TextTemplateFilePath As String = String.Empty
  Private _LoadedTemplate As TemplateItem

  Private _PluginSettings As Settings

  Public Overloads Function ShowDialog(ByVal parent As Object, ByVal pluginSettings As Settings, ByVal textTemplateFilePath As String) As DialogResult
    _PluginSettings = pluginSettings
    _TextTemplateFilePath = textTemplateFilePath
    Return Me.ShowDialog(parent)
  End Function

  Public Overloads Function ShowDialog(ByVal parent As Object, ByVal pluginSettings As Settings) As DialogResult
    _PluginSettings = pluginSettings
    Return Me.ShowDialog(parent)
  End Function

#Region "Form events"
  Private Sub AddTemplate_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

    My.Settings.AddDialogLocation = Me.Location
    My.Settings.AddDialogSize = Me.Size
    My.Settings.Save()

  End Sub

  <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId:="System.Windows.Forms.Control.set_Text(System.String)")> _
  Private Sub AddTemplate_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    If My.Settings.AddDialogLocation.Height > -1 Then
      Me.Location = My.Settings.AddDialogLocation
    End If

    If My.Settings.AddDialogSize.Height > -1 Then
      Me.Size = My.Settings.AddDialogSize
    End If

    LoadCategories()

    _LoadedTemplate = New TemplateItem

    Select Case Me._PluginSettings.LineBreakConversion
      Case Settings.LineBreakConverisonOptions.BRTag
        Me.LinefeedCheckBox.Checked = True
      Case Settings.LineBreakConverisonOptions.NoConversion
        Me.LinefeedCheckBox.Checked = False

      Case Else
        Me.LinefeedCheckBox.Checked = True
    End Select


    'Check to see if we're opening/editing an existing template
    If _TextTemplateFilePath.Length > 0 Then
      Me.Text = "Edit Text Template"

      If IO.File.Exists(_TextTemplateFilePath) Then

        _LoadedTemplate.Load(_TextTemplateFilePath)
        Me.TitleTextBox.Text = _LoadedTemplate.Title

        Select Case Me._PluginSettings.LineBreakConversion
          Case Settings.LineBreakConverisonOptions.BRTag
            Me.HTMLTextBox.Text = Replace(_LoadedTemplate.Insert, "<br>", vbCrLf, , , CompareMethod.Text)

          Case Settings.LineBreakConverisonOptions.NoConversion
            Me.HTMLTextBox.Text = _LoadedTemplate.Insert

          Case Else
            Me.HTMLTextBox.Text = Replace(_LoadedTemplate.Insert, "<br>", vbCrLf, , , CompareMethod.Text)

        End Select

        If _LoadedTemplate.Category.Length = 0 Then
          Me.CategoryComboBox.Text = "None/Blank"
        Else
          Me.CategoryComboBox.Text = _LoadedTemplate.Category

        End If

        Try
          If _LoadedTemplate.IconFile.Length > 0 And _LoadedTemplate.IconIndex > 0 Then
            Dim ic As System.Drawing.Icon = ExtractIcon.GetIcon(_LoadedTemplate.IconFile, _LoadedTemplate.IconIndex)
            Me.IconPictureBox.Image = ic.ToBitmap
            ic.Dispose()

          End If

        Catch ex As Exception

        End Try

      End If

    Else
      Me.Text = "Add Text Template"

    End If

  End Sub


#End Region

#Region "Control Events"

  Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
    Dim WorkingCategory As String = ""

    If TitleTextBox.Text.Length = 0 Then
      ErrorProvider1.SetError(TitleTextBox, "Title is required.")
      Return
    End If

    If Me.CategoryComboBox.Text = "None/Blank" Then
      WorkingCategory = ""
    Else
      WorkingCategory = Me.CategoryComboBox.Text
    End If

    If WorkingCategory.Length > 0 AndAlso Me.CategoryComboBox.Items.IndexOf(WorkingCategory) = -1 Then
      If MsgBox("Add " & Chr(34) & WorkingCategory & Chr(34) & " as a new category?", MsgBoxStyle.YesNo, "Add Category?") = MsgBoxResult.Yes Then
        If My.Settings.Categories.Length > 0 Then
          My.Settings.Categories += "," & WorkingCategory

        Else
          My.Settings.Categories = WorkingCategory

        End If
        My.Settings.Save()
      End If

    End If

    If _TextTemplateFilePath.Length > 0 Then

      _LoadedTemplate.Title = TitleTextBox.Text
      _LoadedTemplate.Insert = GetHTML(HTMLTextBox.Text)

      _LoadedTemplate.Category = WorkingCategory

      _LoadedTemplate.TemplateFilePath = _TextTemplateFilePath
      _LoadedTemplate.Save()

    ElseIf _PluginSettings.TemplatePath.Length > 0 Then

      If IO.Directory.Exists(_PluginSettings.TemplatePath) = False Then
        IO.Directory.CreateDirectory(_PluginSettings.TemplatePath)
      End If

      Try
        Me.SaveFileDialog1.InitialDirectory = _PluginSettings.TemplatePath
        Me.SaveFileDialog1.FileName = IO.Path.Combine(_PluginSettings.TemplatePath, TitleTextBox.Text)

      Catch ex As Exception

      End Try

      If Me.SaveFileDialog1.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
        _LoadedTemplate.Title = TitleTextBox.Text
        _LoadedTemplate.Insert = GetHTML(HTMLTextBox.Text)

        _LoadedTemplate.Category = WorkingCategory

        _LoadedTemplate.TemplateFilePath = IO.Path.Combine(_PluginSettings.TemplatePath, Me.SaveFileDialog1.FileName)

        _LoadedTemplate.Save()

      End If

    End If

    Me.DialogResult = System.Windows.Forms.DialogResult.OK
    Me.Close()

  End Sub

  Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
    Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
    Me.Close()
  End Sub

  Private Sub TitleTextBox_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TitleTextBox.Validating
    If TitleTextBox.Text.Length = 0 Then
      ErrorProvider1.SetError(TitleTextBox, "Title is required.")
    End If

  End Sub

  Private Sub OpenFolderLinkLabel_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles OpenFolderLinkLabel.LinkClicked
    If IO.Directory.Exists(_PluginSettings.TemplatePath) Then
      Try
        Process.Start(_PluginSettings.TemplatePath)
      Catch ex As Exception
        MsgBox("Error opening folder, " & _PluginSettings.TemplatePath & vbCrLf & vbCrLf & "Error: " & ex.Message, , "Error Opening Folder")
      End Try

    Else
      MsgBox("The folder, " & _PluginSettings.TemplatePath & " does not exist. This could be because new paths that are manually typed in will not be created until OK is clicked...", , "Folder Does Not Exist")
    End If

  End Sub

  Private Sub SelectIconButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectIconButton.Click

    Dim s As New Text.StringBuilder(500)
    If _LoadedTemplate.IconFile.Length > 0 Then
      s.Append(_LoadedTemplate.IconFile)
		Else
			s.Append(io.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.System) , "shell32.dll"))
    End If

    Dim i As Integer = _LoadedTemplate.IconIndex
    Dim x As Integer = ExtractIcon.UnsafeNativeMethods.PickIconDlg(Me.Handle, s, s.Capacity, i)

    If x = 1 Then
      _LoadedTemplate.IconIndex = i
      _LoadedTemplate.IconFile = s.ToString
      Me.IconPictureBox.Image = _LoadedTemplate.Icon.ToBitmap

    End If

  End Sub

  Private Sub PreviewLinkLabel_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles PreviewLinkLabel.LinkClicked
    Dim frm As InsertPreview
    Dim Insert As String = GetHTML(Me.HTMLTextBox.Text)

    frm = New InsertPreview

    Try
      frm.ShowDialog(Me, Insert)
    Catch ex As Exception
      MsgBox("Error showing the Preview " & Err.Description)
    End Try

    frm.Dispose()

  End Sub

  Private Sub CategoryComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CategoryComboBox.SelectedIndexChanged
    If Me.CategoryComboBox.Text = "[Manage Categories]" Then
      Dim frm As New ManageCategories
      If frm.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
        LoadCategories()
      End If
    End If

  End Sub

  Private Sub LinefeedCheckBox_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinefeedCheckBox.Click

    If LinefeedCheckBox.Checked Then
      Me._PluginSettings.LineBreakConversion = Settings.LineBreakConverisonOptions.BRTag
    Else
      Me._PluginSettings.LineBreakConversion = Settings.LineBreakConverisonOptions.NoConversion
    End If

  End Sub

#End Region

#Region "Private helpers"

  Private Sub LoadCategories()
    Me.CategoryComboBox.Items.Clear()

    Me.CategoryComboBox.Items.Add("None/Blank")

    Try
      If My.Settings.Categories.Length > 0 Then
        Dim x() As String = My.Settings.Categories.Split(",")
        Array.Sort(x)
        Me.CategoryComboBox.Items.AddRange(x)
      End If

    Catch ex As Exception

    End Try

    Me.CategoryComboBox.Items.Add("[Manage Categories]")


  End Sub

  Private Function GetHTML(ByVal Source As String) As String

    Select Case _PluginSettings.LineBreakConversion
      Case Settings.LineBreakConverisonOptions.BRTag
        GetHTML = Replace(HTMLTextBox.Text, vbCrLf, "<br>", , , CompareMethod.Text)

      Case Settings.LineBreakConverisonOptions.NoConversion
        GetHTML = HTMLTextBox.Text

      Case Else
        GetHTML = Replace(HTMLTextBox.Text, vbCrLf, "<br>", , , CompareMethod.Text)

    End Select

  End Function

#End Region



End Class
